#include "Log.h"

#include <iostream>
#include <ctime>

Log Log::theInstance;

Log& Log::getInstance()
{
	return theInstance;
}

bool Log::initialize(const char* logFile, std::ofstream*	logBuffer, bool quiet)
{
	if (isInitialized)
		return true;

	static const char* welcomeMessage =
		"Log System started...";

	isInitialized = true;
	quietMode = quiet;

	pLogBuffer = NULL;
	coutbuf = NULL;
	if (NULL == logFile || NULL == logBuffer || 0 == strcmp("none", logFile))
	{
		if (! quietMode)
			log(welcomeMessage);
		return true;
	}
	// Save Old Buffer
	coutbuf = std::cout.rdbuf();
	pLogBuffer = logBuffer;
	pLogBuffer->open (logFile, std::ofstream::out | std::ofstream::app);
	std::cout.rdbuf(logBuffer->rdbuf());
	log(welcomeMessage);
	return true;
}
bool Log::reDirect(const char* logFile, std::ofstream*	logBuffer)
{
	if (NULL == logFile)
		return true;
	isInitialized = false;
	return initialize(logFile, logBuffer, quietMode);
}

bool Log::shutdown()
{
	if (! isInitialized)
		return true;

	static const char* finalMessage =
		"Log System shutting down...";

	if (! quietMode)
		log(finalMessage);

	if (NULL != coutbuf)
	{
		std::cout.rdbuf(coutbuf);
		pLogBuffer->close();
	}
	isInitialized = false;
	return true;
}

void Log::log(const char* message, bool showTimeStamp)
{
	if (!isInitialized)
	{
		const char* default_msg = "Log not Initialized!\n";
		std::cout << default_msg << message << std::endl;
		return;
	}


	if (! showTimeStamp )
	{
		std::cout << message << std::endl;
		return;
	}

	// current date/time based on current system
	time_t now = time(0);
	struct tm timeinfo;
	localtime_s(&timeinfo, &now);
	//tm *ltm = localtime(&now);
	std::cout << "[" << timeinfo.tm_mday << "/"
		<< 1 + timeinfo.tm_mon << "/"
		<< 1900 + timeinfo.tm_year << "] ("
		<<   1 + timeinfo.tm_hour << ":"
		<<   1 + timeinfo.tm_min << ":"
		<<   1 + timeinfo.tm_sec << ") "
		<<   message << std::endl;
} 